#!/bin/bash

# Function to update playlist file with new segments
update_playlist() {
    local playlist_file="$1"
    local base_duration=0  # Initialize with 0 to start

    # Read the last duration from the playlist if it exists
    if [ -f "$playlist_file" ]; then
        # Try to extract the last known duration if available
        local last_duration=$(grep -oP '#EXTINF:\K[\d\.]+' "$playlist_file" | tail -1)
        if [ -n "$last_duration" ]; then
            base_duration=$last_duration
        fi
    else
        # Initialize the playlist file with headers
        echo "#EXTM3U" > "$playlist_file"
        echo "#EXT-X-VERSION:3" >> "$playlist_file"
        echo "#EXT-X-TARGETDURATION:60" >> "$playlist_file"
        echo "#EXT-X-MEDIA-SEQUENCE:0" >> "$playlist_file"
    fi

    # Shift the first argument to get segment files
    shift
    local segment_files=("$@")

    # Add new segment entries to playlist.m3u8
    for file in "${segment_files[@]}"; do
        local filename=$(basename "$file")
        local duration=$(ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "$file")
        local adjusted_duration=$(echo "$base_duration + $duration" | bc)
        echo "#EXTINF:${adjusted_duration}," >> "$playlist_file"
        echo "$filename" >> "$playlist_file"
        # Update the base duration for the next iteration
        base_duration=$adjusted_duration
    done

    # Update or add the EXT-X-ENDLIST tag at the end of playlist.m3u8
    sed -i '/#EXT-X-ENDLIST/d' "$playlist_file"
    echo "#EXT-X-ENDLIST" >> "$playlist_file"
}

# Check if input parameters are provided
if [ $# -lt 2 ]; then
    echo "Usage: $0 <absolute_path_to_video> <output_directory>"
    exit 1
fi

# Input video file path
input_file="$1"
# Output directory for the playlist.m3u8 and ts files
output_dir="$2"

# Check if input file exists
if [ ! -f "$input_file" ]; then
    echo "Error: Input file not found: $input_file"
    exit 1
fi

# Ensure the output directory exists, create if not
if [ ! -d "$output_dir" ]; then
    mkdir -p "$output_dir"
fi

# Base name of the input file (without extension)
base_name=$(basename "$input_file" | cut -d. -f1)

# Output file name for the playlist.m3u8
playlist_file="$output_dir/playlist.m3u8"

# Execute ffmpeg command to convert and segment the video
ffmpeg -i "$input_file" -codec:v copy -bsf:v h264_mp4toannexb \
       -f segment -segment_time 60 -segment_format mpegts \
       "$output_dir/${base_name}_$(date +%s)-%03d.ts"

# Find all segment files matching the base_name pattern
mapfile -t new_segments < <(find "$output_dir" -maxdepth 1 -type f -name "$base_name*.ts" | sort)

# Update playlist.m3u8 with new segment entries
update_playlist "$playlist_file" "${new_segments[@]}"

# Inform user about completion
echo "Conversion and segmentation completed. Playlist: $playlist_file"
